package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/mq")
@Slf4j
public class MqController {

    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 确认发送消息
     * @return
     */
    @GetMapping("sendConfirm")
    public Result sendMesag(){
        rabbitService.sendMessage("exchange.confirm","routing.confirm","你来玩吧");
            return Result.ok();
    }

    /**
     * 基础延迟队列发送延迟消息
     * @return
     */
    @GetMapping("sendDeadLettle")
    public Result sendDeadLettle(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(new Date());
        System.out.println("发送消息的时间为"+format1);
        rabbitService.sendMessage(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"10秒消息发送");
        return Result.ok();
    }


    /**
     * 基础插件发送延迟消息
     * @return
     */
    @GetMapping("sendDelay")
    public Result sendDeadLettle2(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(new Date());

        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "我是基础插件发送延迟消息", new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {

//                设置延迟时间
                System.out.println("发送消息的时间为"+format1);
                message.getMessageProperties().setDelay(10*1000);
                return message;
            }
        });
        return Result.ok();
    }

}
